<template>
  <div id="chart" class="encecharts"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
]);

const colors = ["#165DFF", "#2CB8C5"];
const xAxisData = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
const data = {
  yName: [
    {
      name: "",
    },
    {
      name: "", 
    },
  ],
  data: [
    {
      name: "我",
      data: [64, 159, 112, 86, 151, 131, 118, 232, 23],
    },
    {
      name: "济南市",
      
      data: [124, 30, 77, 97, 67, 75, 70, 334, 123],
    },
  ],
};

const option = {
  tooltip: {
    trigger: "axis",
  },
  grid: {
    top: "40",
    left: 0,
    right: 20,
    bottom: "30",
    containLabel: true,
  },
  
  legend: {

    textStyle: {
      color: "#4E5969",
    },
    data: data.data.map((item) => item.name),
  },
  xAxis: [
    {
      type: "category",
      data: xAxisData,
      axisPointer: {
        type: "shadow",
      },
      axisLine: {
        lineStyle: {
          color: "rgba(28,31,35,0.8)",
        },
      },
    },
  ],
  yAxis: data.yName.map((item) => ({
    type: "value",
    name: item.name,
    nameTextStyle: {
      color: "#86909C",
    },
    axisLabel: {
      formatter: "{value}",
      textStyle: {
        color: "#86909C",
      },
    },
    axisLine: {
      lineStyle: {
        color: "#1c1f23",
      },
    },
    splitLine: {
      lineStyle: {
        color: "#e6e8ea",
        type: "dashed",
      },
    },
  })),
  series: data.data.map((item, index) => ({
    name: item.name,
    type: "line",
    yAxisIndex: index,
    smooth: true,
    color: colors[index],
    tooltip: {
      valueFormatter: function (value) {
        return value;
      },
    },
    data: item.data,
  })),
};

let chart;
onMounted(() => {
  chart = echarts.init(document.getElementById("chart"));
  chart.setOption(option);

  // 监听窗口大小变化事件
  window.addEventListener("resize", handleResize);
});

const handleResize = () => {
  chart && chart.resize();
};

onBeforeUnmount(() => {
  // 移除窗口大小变化事件监听器
  window.removeEventListener("resize", handleResize);
  chart && chart.dispose();
});
</script>

<style lang="less" scoped>
#chart {
  width: 100%;
  height: 100%;
}
.encecharts {
  width: 100%;
  height: 100%;
}
</style>
